import { queryOptions } from "@tanstack/react-query";
import type { InferResponseType } from "hono/client";
import { authClient } from "@/lib/auth-client";
import { client } from "@/lib/rpc";

export const sessionQueryOptions = queryOptions({
  queryKey: ["session"],
  queryFn: async () => {
    const { data } = await authClient.getSession();
    return data ?? null;
  },
  staleTime: 30 * 60 * 1000,
});

const $orgs = client.orgs.$get;
type OrgsWithMembersData = InferResponseType<typeof $orgs>;
export type OrgWithMembers = OrgsWithMembersData["data"][number];
export type Member = OrgsWithMembersData["data"][number]["members"][number];

export function orgsQueryOptions(userId: string) {
  return queryOptions({
    queryKey: ["organizations", userId],
    queryFn: async () => {
      const res = await client.orgs.$get({ query: { userId } });
      if (!res.ok) throw new Error("Failed to fetch organizations");
      const data = await res.json();
      if (!data.ok || data.data === null) throw new Error("Failed to fetch organizations");
      return data.data;
    },
    enabled: !!userId,
  });
}
